package com.lsl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.entity.BlogVote;
import com.lsl.mapper.BlogVoteMapper;
import com.lsl.service.BlogVoteService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BlogVoteServiceImpl extends ServiceImpl<BlogVoteMapper, BlogVote> implements BlogVoteService {

    @Override
    @Transactional
    public boolean vote(Integer blogId, Integer userId, Integer voteType) {
        // 先删除原有投票记录
        lambdaUpdate()
            .eq(BlogVote::getBlogID, blogId)
            .eq(BlogVote::getUserID, userId)
            .remove();
        
        // 插入新投票记录
        BlogVote vote = new BlogVote();
        vote.setBlogID(blogId);
        vote.setUserID(userId);
        vote.setVoteType(voteType);
        return save(vote);
    }

    @Override
    public Integer getVoteCount(Integer blogId, Integer voteType) {
        return lambdaQuery()
            .eq(BlogVote::getBlogID, blogId)
            .eq(BlogVote::getVoteType, voteType)
            .count()
            .intValue();
    }

    @Override
    public Integer getVoteType(Integer blogId, Integer userId) {
        BlogVote vote = lambdaQuery()
            .eq(BlogVote::getBlogID, blogId)
            .eq(BlogVote::getUserID, userId)
            .one();
        return vote != null ? vote.getVoteType() : 0;
    }

    @Override
    @Transactional
    public boolean changeVote(Integer blogId, Integer userId, Integer newVoteType) {
        return lambdaUpdate()
            .eq(BlogVote::getBlogID, blogId)
            .eq(BlogVote::getUserID, userId)
            .set(BlogVote::getVoteType, newVoteType)
            .update();
    }

    @Override
    @Transactional
    public boolean removeVote(Integer blogId, Integer userId) {
        return lambdaUpdate()
            .eq(BlogVote::getBlogID, blogId)
            .eq(BlogVote::getUserID, userId)
            .remove();
    }
}
